package com.iqilu.ksd.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.SubsBean;
import com.iqilu.ksd.bean.SubsItemBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 添加订阅
 * Created by Coofee on 2016/11/16.
 */

public class AddSubscribeActivity extends BaseActivity {

    public ArrayList<SubsBean> list;
    public ArrayList<SubsItemBean> childList;

    public ParentAdapter parentAdapter;
    public ChildAdapter childAdapter;
    private LigDialog ligDialog;

    private ImageView btLeft;
    private ImageView btRight;
    private TextView tvtitle;
    private ListView lvParent;
    private ListView lvChild;
    private ImageView imgEmpty;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addsubscribe);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        getList();
    }

    private void initView() {
        btLeft = getView(R.id.bt_left);
        btRight = getView(R.id.bt_right);
        tvtitle = getView(R.id.tv_title);
        setZHTypeface(tvtitle);
        lvParent = getView(R.id.lv_parent);
        lvChild = getView(R.id.lv_child);
        imgEmpty = getView(R.id.img_empty);
        tvtitle.setText(getString(R.string.my_add_column));
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                setResult(Activity.RESULT_OK);
                finish();
            }
        });
        btRight.setImageResource(R.drawable.bt_search);
        btRight.setVisibility(View.VISIBLE);
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AddSubscribeActivity.this,SubsSearchActivity.class));
            }
        });
        childAdapter = new ChildAdapter();
        lvChild.setAdapter(childAdapter);
        lvChild.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(AddSubscribeActivity.this,SubsDetailActivity.class);
                intent.putExtra("catid",childList.get(position).getCatid());
                startActivity(intent);
            }
        });
        lvParent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                list.get(position).setClicked(true);
                for (int j = 0; j < list.size(); j++) {
                    if (j == position) {
                        list.get(j).setClicked(true);
                    } else {
                        list.get(j).setClicked(false);
                    }
                }
                parentAdapter.notifyDataSetChanged();
                childList = list.get(position).getCates();
                childAdapter.notifyDataSetChanged();
            }
        });
    }

    private void getList() {
        String url = Api.URL_CATE;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(AddSubscribeActivity.this, getString(R.string.waiting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
                imgEmpty.setVisibility(View.VISIBLE);
                Toast.makeText(AddSubscribeActivity.this, R.string.load_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                list = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<SubsBean>>() {
                });
                if (list != null && list.size() > 0) {
                    list.get(0).setClicked(true);
                    parentAdapter = new ParentAdapter();
                    lvParent.setAdapter(parentAdapter);
                    childList = list.get(0).getCates();
                    childAdapter.notifyDataSetChanged();
                } else {
                    imgEmpty.setVisibility(View.VISIBLE);
                    Toast.makeText(AddSubscribeActivity.this, R.string.load_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void addColumn(final int position) {
        int catid = childList.get(position).getCatid();
        String catname = childList.get(position).getCatname();
        String type = childList.get(position).getType();
        String url = Api.URL_SUBSCRIBE + "?catid=" + catid + "&catname=" + catname + "&type=" + type;
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(RequestBody.create(null, "something"))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(AddSubscribeActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            status = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (status == 1) {
                            childList.get(position).setSubscribed(1);
                            childAdapter.notifyDataSetChanged();
                            Toast.makeText(AddSubscribeActivity.this, R.string.my_add_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(AddSubscribeActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void delColumn(final int position) {
        int catid = childList.get(position).getCatid();
        String type = childList.get(position).getType();
        String url = Api.URL_SUBSCRIBE + "?catid=" + catid + "&type=" + type;
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(AddSubscribeActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    status = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (status == 1) {
                    childList.get(position).setSubscribed(0);
                    childAdapter.notifyDataSetChanged();
                    Toast.makeText(AddSubscribeActivity.this, R.string.my_del_success, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AddSubscribeActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void finish() {
        setResult(Activity.RESULT_OK);
        super.finish();
    }

    class ParentAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(AddSubscribeActivity.this).inflate(R.layout.list_item_addsubscribe_parent, null);
                holder.layoutContent = (RelativeLayout) view.findViewById(R.id.layout_content);
                holder.imgLine = (ImageView) view.findViewById(R.id.img_line);
                holder.txtTitle = (TextView) view.findViewById(R.id.tv_title);
                setZHTypeface(holder.txtTitle);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.txtTitle.setText("" + list.get(i).getCatname());
            if (list.get(i).getClicked() != null && list.get(i).getClicked()) {
                holder.imgLine.setVisibility(View.VISIBLE);
                holder.layoutContent.setBackgroundColor(Color.WHITE);
            } else {
                holder.imgLine.setVisibility(View.INVISIBLE);
                holder.layoutContent.setBackgroundColor(getResources().getColor(R.color.background));
            }
            return view;
        }

        class ViewHolder {
            RelativeLayout layoutContent;
            ImageView imgLine;
            TextView txtTitle;
        }
    }

    class ChildAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return childList == null ? 0 : childList.size();
        }

        @Override
        public Object getItem(int i) {
            return childList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(AddSubscribeActivity.this).inflate(R.layout.list_item_addsubscribe_child, null);
                holder.imgThumb = (SimpleDraweeView) view.findViewById(R.id.img_thumb);
                holder.btAdd = (ImageView) view.findViewById(R.id.bt_add);
                holder.tvTitle = (TextView) view.findViewById(R.id.tv_title);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.tvTitle.setText("" + childList.get(i).getCatname());
            holder.imgThumb.setImageURI(Uri.parse(childList.get(i).getThumb()));
            if (childList.get(i).getSubscribed() == 1) {
                holder.btAdd.setImageResource(R.drawable.bt_subscribed);
            } else {
                holder.btAdd.setImageResource(R.drawable.bt_subscribe);
            }
            holder.btAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!NetworkUtils.isAvailable(AddSubscribeActivity.this)) {
                        Toast.makeText(AddSubscribeActivity.this, R.string.net_not_connected, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (childList.get(i).getSubscribed() == 1) {
                        delColumn(i);
                    } else {
                        addColumn(i);
                    }
                }
            });
            return view;
        }

        class ViewHolder {
            SimpleDraweeView imgThumb;
            TextView tvTitle;
            ImageView btAdd;
        }
    }
}
